package com.dpxm.zdbdg.chart.daletou.service;

import com.alibaba.fastjson.JSONObject;
import com.dpxm.zdbdg.chart.daletou.dao.DaLeTouDao;
import com.dpxm.zdbdg.chart.daletou.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import vehiclebase.enums.QueryEnum;
import vehiclebase.utils.BusinessException;
import vehiclebase.utils.ToolsUtils;
import com.alibaba.fastjson.JSON;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ChartService {
    @Autowired
    private DaLeTouDao daLeTouDao;

    /**
     * 查询大乐透信息
     * @param front
     ** @param rear
     * @return
     */
    public List<QueryDaLeTouVO> view(String front, String rear) {
        if(ToolsUtils.isEmpty(front) && ToolsUtils.isEmpty(rear)){
            throw new BusinessException("期数不能为空" );
        }
        List<QueryDaLeTouVO> queryDaLeTou = daLeTouDao.QueryDaLeTou(front,rear);

        return queryDaLeTou;
    }


    /**
     * 分析冷热号
     * @return
     */
    public coldHotRes coldHot() {
        coldHotRes coldHot = new coldHotRes();
        //大乐透官网 对象
        PtQueryDaLeTouVO ptQueryDaLe = new PtQueryDaLeTouVO();
        RestTemplate restTemplate = new RestTemplate();
        String daLetTouLiShi = restTemplate.getForObject("https://webapi.sporttery.cn/gateway/lottery/getHistoryPageListV1.qry?gameNo=85&provinceId=0&pageSize=30&isVerify=1&pageNo=1", String.class);
        //将官网的数据转化为自有对象
        ptQueryDaLe = JSONObject.parseObject(daLetTouLiShi, PtQueryDaLeTouVO.class);
        if(ToolsUtils.notEmpty(ptQueryDaLe) && ptQueryDaLe.getErrorMessage().equals(QueryEnum.ERROR_MESSAGE.val())){
            List<Values> valueList = ptQueryDaLe.getValue().getList();
            //将数据存入本地库
            QueryDaLeTouVO queryDaLeTouVO = new QueryDaLeTouVO();
            if(ToolsUtils.notEmpty(valueList)){
                String numbe = valueList.get(0).getLotteryDrawResult(); //取到最新的开奖号码
                List<String> listnNumbe = Arrays.asList(numbe.split(" "));
                //List<String> 转化为List<Integer>
                List<Integer> listNumbeInsr = listnNumbe.stream().map(Integer::parseInt).collect(Collectors.toList());
                queryDaLeTouVO.setQ_one(listNumbeInsr.get(0));
                queryDaLeTouVO.setQ_two(listNumbeInsr.get(1));
                queryDaLeTouVO.setQ_three(listNumbeInsr.get(2));
                queryDaLeTouVO.setQ_four(listNumbeInsr.get(3));
                queryDaLeTouVO.setQ_five(listNumbeInsr.get(4));
                queryDaLeTouVO.setH_one(listNumbeInsr.get(5));
                queryDaLeTouVO.setH_two(listNumbeInsr.get(6));
                queryDaLeTouVO.setQihao(valueList.get(0).getLotteryDrawNum());
                queryDaLeTouVO.setCreatedate(valueList.get(0).getLotteryDrawTime());
                //存入数据之前查询是否有当期数据
                QueryDaLeTouVO QueryDangQiDaLeTou = daLeTouDao.QueryDangQi(valueList.get(0).getLotteryDrawNum());
                //没有数据查询
                if(ToolsUtils.isEmpty(QueryDangQiDaLeTou)){
                    daLeTouDao.insertSelective(queryDaLeTouVO);
                }
            }

        }


        //查询出最近16期开奖信息
        List<QueryDaLeTouVO> queryMessage = daLeTouDao.QueryMessage(QueryEnum.QUERY_QIHAO.val());
        List<Integer> hong = new ArrayList<>();
        //此集合为16期内的所有开奖号码。 16期内出险过4次的号码为热号
        if(ToolsUtils.notEmpty(queryMessage)){
            queryMessage.forEach(a->{
                hong.add(a.getQ_one());
                hong.add(a.getQ_two());
                hong.add(a.getQ_three());
                hong.add(a.getQ_four());
                hong.add(a.getQ_five());
            });
        }
        //热号分析 （16期内出现过4次及的号码为热号）
        getHotNumb(hong,coldHot);
        //冷号分析 （16期没有出现过的号码冷号）
        getCotNumb(hong,coldHot);
        //组装返回的数据
        getMessage(coldHot);
        return coldHot;
    }

    /**
     * 组装返回的数据
     * @param coldHot
     * @return
     */
    public void  getMessage(coldHotRes coldHot){
        //冷号
        StringBuffer coldNumber = new StringBuffer();
        coldNumber.append("冷号：");
        List<String> coldList = coldHot.getColdNumber();
        for (int i=0 ;i<coldList.size() ; i++){
            coldNumber.append(" "+coldList.get(i));
        }

        //热号
        StringBuffer hotNumber = new StringBuffer();
        hotNumber.append("热号：");
        List<String> hotList = coldHot.getHotNumber();
        for (int i=0 ;i<hotList.size() ; i++){
            hotNumber.append(" "+hotList.get(i));
        }

        //调整红球的格式
        StringBuffer Number = new StringBuffer();
        List<JXZuHeVO> numberList = new ArrayList<>();//返回机选五注的List

        //机选五注
        for (int k=0 ;k<5 ; k++){
            JXZuHeVO jXZuHeVO = new JXZuHeVO();
            //机选 冷号
            Random random = new Random();
            int num = random.nextInt(coldList.size());

            System.out.println(coldList.get(num));
            //机选 热号
            List<String> jxHotNumber = new ArrayList<>();
            for (int i=0 ;i<20 ; i++){
                Random randomss = new Random();
                int nums = randomss.nextInt(hotList.size());
                String shu=hotList.get(nums);
                //判断jxHotNumber是否含有shu
                if (jxHotNumber.stream().filter(w->String.valueOf(w.toString()).equals(shu)).findAny().isPresent()){
                    continue;
                }
                jxHotNumber.add(shu);
                if(jxHotNumber.size()==3){
                    break;
                }
            }
            //把温热号也放进去
            Random randoms = new Random();
            int numNotHotNumb = randoms.nextInt(coldHot.getNotHotNumb().size());
            jxHotNumber.add(coldHot.getNotHotNumb().get(numNotHotNumb));
            //把冷号也放进去
            jxHotNumber.add(coldList.get(num));
            //机选两位篮球
            List<String> modes = new ArrayList<>();
            for (int i=1; i<=12; i++){ //模拟1-12
                modes.add(String.valueOf(i));
            }
            //最终篮球的号码
            List<String> jxLanHotNumber = new ArrayList<>();
            for (int i=0 ;i<20 ; i++){
                Random randomss = new Random();
                int nums = randomss.nextInt(modes.size());
                String shu=modes.get(nums);
                if (jxLanHotNumber.stream().filter(w->String.valueOf(w.toString()).equals(shu)).findAny().isPresent()){
                    continue;
                }
                jxLanHotNumber.add(shu);
                if(jxLanHotNumber.size()==2){
                    break;
                }
            }
            //List<String> 转化为List<Integer>
            List<Integer> codesInteger = jxHotNumber.stream().map(Integer::parseInt).collect(Collectors.toList());
            //排序
            Collections.sort(codesInteger);
            //最终的红球
            List<String> cotNumbs = codesInteger.stream().map(String::valueOf).collect(Collectors.toList());
            //List<String> 转化为List<Integer>
            List<Integer> codesIntegerlanqiu = jxLanHotNumber.stream().map(Integer::parseInt).collect(Collectors.toList());
            //排序
            Collections.sort(codesIntegerlanqiu);
            //最终的篮球
            List<String> lanqiu = codesIntegerlanqiu.stream().map(String::valueOf).collect(Collectors.toList());
            Number.append("第"+k+"注: ");
            StringBuffer hong = new StringBuffer();
            StringBuffer lan = new StringBuffer();
            for (int i=0 ;i<cotNumbs.size() ; i++){
                String str="";
                if(cotNumbs.get(i).length()==1){
                     str="0"+cotNumbs.get(i);
                }else {
                    str=cotNumbs.get(i);
                }
                Number.append(str+" ");
                hong.append(str+" ");
            }
            Number.append(" + ");
            for (int j=0 ;j<lanqiu.size() ; j++){
                String str="";
                if(lanqiu.get(j).length()==1){
                    str="0"+lanqiu.get(j);
                }else {
                    str=lanqiu.get(j);
                }
                Number.append(str+" ");
                lan.append(str+" ");
            }
            jXZuHeVO.setBenqiHongQiuNumber(hong.toString());
            jXZuHeVO.setBenqiLanQiuNumber(lan.toString());
            numberList.add(jXZuHeVO);
            Number.append(" | ");



        }

        coldHot.setNumbers(Number.toString());
        coldHot.setBenqiColdNumber(coldNumber.toString());
        coldHot.setBenqiHotNumber(hotNumber.toString());
        coldHot.setNumberList(numberList);
    }

    /**
     * 冷号分析
     * @param hong
     * @param coldHot
     * @return
     */
    public void getCotNumb(List<Integer> hong,coldHotRes coldHot){
        //冷号需要先去重复
        List<Integer> cotList=hong.stream().distinct().collect(Collectors.toList());
        //排序
        Collections.sort(cotList);
        //List<Integer> 转化为List<String>
        List<String> string2 = cotList.stream().map(String::valueOf).collect(Collectors.toList());
        List<String> modes = new ArrayList<>();
        for (int i=1; i<=35; i++){ //模拟1-35
            modes.add(String.valueOf(i));
        }
        // 平台有，业务表没有
        List<String> cotNumb = modes.stream().filter(a->!string2.contains(a)).collect(Collectors.toList());
        //List<String> 转化为List<Integer>
        List<Integer> codesInteger = cotNumb.stream().map(Integer::parseInt).collect(Collectors.toList());
        //排序
        Collections.sort(codesInteger);
        List<String> cotNumbs = codesInteger.stream().map(String::valueOf).collect(Collectors.toList());
        coldHot.setColdNumber(cotNumbs);
    }

    /**
     * 热号分析
     * @param hong
     * @param coldHot
     * @return
     */
    public void  getHotNumb(List<Integer> hong,coldHotRes coldHot){
        Map<Integer,Integer> map = new HashMap<>();
        for(Integer str:hong){
            Integer i = 1; //定义一个计数器，用来记录重复数据的个数
            if(map.get(str) != null){
                i=map.get(str)+1;
            }
            map.put(str,i);
        }
        // System.out.println("重复数据的个数："+map.toString());
        //热号的集合
        List<Integer> hotNumb = new ArrayList<>();
        //热不温的集合 小于4
        List<Integer> notHotNumb = new ArrayList<>();
        //16期内出险过4次及的号码为热号
        for (Integer key : map.keySet()) {
            if(map.get(key) >=4){
                hotNumb.add(key);
            }else {
                notHotNumb.add(key);
            }
        }
        //排序
        Collections.sort(hotNumb);
        Collections.sort(notHotNumb);
        //List<Integer> 转化为List<String>
        List<String> hotNumbs = hotNumb.stream().map(String::valueOf).collect(Collectors.toList());
        List<String> notHotNumbs = notHotNumb.stream().map(String::valueOf).collect(Collectors.toList());
        coldHot.setHotNumber(hotNumbs);
        coldHot.setNotHotNumb(notHotNumbs);
    }
}
